//
//  GWAlbumRecommendationsView.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/4.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import SnapKit

protocol GWAlbumRecommendationsViewDelegate {
  func gwAlbumRecommendationsView(_ view: GWAlbumRecommendationsView, selectedWithAlbumIdentifier: Int)
}

class GWAlbumRecommendationsView: UIView {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var scrollView: UIScrollView!
  @IBOutlet private weak var pageControl: UIPageControl!
  
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  
  
  // MARK: - Public vars
  
  var delegate: GWAlbumRecommendationsViewDelegate?
  
  // MARK: - Lifecycle
  
  
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  func prepare(albums: [Album]) {
    
    scrollView.subviews.forEach {
      if type(of: $0) == GWAlbumRecommendationItem.self {
        $0.removeFromSuperview()
      }
    }
    
    // scroll
    var prevItem: GWAlbumRecommendationItem?
    for (index, album) in albums.enumerated() {
      let item: GWAlbumRecommendationItem = .fromNib()
      item.delegate = self
      item.prepare(album: album)
      scrollView.addSubview(item)
      item.snp.makeConstraints { maker in
        maker.height.equalTo(GWAlbumRecommendationItem.defaultHeight)
        maker.width.equalTo(self.snp.width)
        maker.top.equalTo(0)
        if index == 0 {
          maker.leading.equalTo(0)
        } else {
          if let prevItem = prevItem {
            maker.leading.equalTo(prevItem.snp.trailing)
          }
          if index == albums.count - 1 {
            maker.trailing.equalTo(0)
          }
        }
      }
      prevItem = item
    }
    
    // page
    pageControl.numberOfPages = albums.count
  }
}

// MARK: - UIScrollViewDelegate

extension GWAlbumRecommendationsView: UIScrollViewDelegate {
  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let page = scrollView.contentOffset.x / scrollView.width
    pageControl.currentPage = Int(page)
  }
}

// MARK: - GWAlbumRecommendationItemDelegate

extension GWAlbumRecommendationsView: GWAlbumRecommendationItemDelegate {
  func gwAlbumRecommendationItem(_ item: GWAlbumRecommendationItem, tappedWithAlbumIdentifier: Int) {
    delegate?.gwAlbumRecommendationsView(self, selectedWithAlbumIdentifier: tappedWithAlbumIdentifier)
  }
}
